window.onload = function(){
    var ul = document.querySelector(".firstnav ul");
    var fsection = document.querySelector(".tabscon")
    var tabadd = document.querySelector(".tabadd span")
    updateNode()
    function updateNode() {
        var lis = document.querySelectorAll(".firstnav ul li");
        var sections = document.querySelectorAll(".tabscon section");
        var removes = document.querySelectorAll(".firstnav ul li span:nth-child(2)")
        init(lis,sections,removes)
    }
    // init 初始化操作让相关元素绑定事件
    function init(lis,sections,removes) {
        console.log(tabadd);
        tabadd.onclick = function(){
            Add(lis,sections)
        }
        for (var i = 0; i < lis.length; i++) {
            lis[i].index = i
            removes[i].index = i
            lis[i].onclick = function(){
                let s = this.index;
                clearClass(lis,sections)
                toggleTab(lis,s,sections)
                
            };
            removes[i].onclick = function(e){
                let s = this.index;
                // console.log(s)
                e.stopPropagation();
                Delete(lis,sections,s)
            }
        }
        // toggleTab(lis,i,sections)
    }

    // 清除所有的li和reaction
    function clearClass(lis,sections) {  
        for (var j = 0; j < lis.length; j++) {
            lis[j].className = "";
            sections[j].className = "";
        }
    }
    // 切换
    function toggleTab(lis,index,sections) {
        console.log(index)
        lis[index].className = "liactive";
        sections[index].className = "conactive";
    }
    //增加
    function Add(lis,sections){
        clearClass(lis,sections);
        var random = Math.random();
        var li = '<li class="liactive"><span>新选项卡</span><span class="iconfont icon-guanbi">×</span></li>';
        var section = '<section class="conactive">测试' + random + '</section>';
        ul.insertAdjacentHTML("beforeend",li);
        fsection.insertAdjacentHTML("beforeend",section)
        updateNode()
    }
    //删除
    function Delete(lis,sections,s){
        if(lis[s].className=='liactive'){
            let i = s-1;
            if(i<0){
                i = s+1
            }
            clearClass(lis,sections)
            toggleTab(lis,i,sections)
        }

        lis[s].remove()
        sections[s].remove()

        updateNode()
        
    }
}